package com.zhuxiang.service.impl;

import com.zhuxiang.common.Salt;
import com.zhuxiang.dao.UserDao;
import com.zhuxiang.entity.User;
import com.zhuxiang.service.UserService;
import com.zhuxiang.util.PasswordEncoder;
import com.zhuxiang.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Date;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public String save(User user) {
        if (StringUtil.isNotEmpty(user.getUserName()) &&
                StringUtil.isNotEmpty(user.getCellphone()) &&
                StringUtil.isNotEmpty(user.getEmail()) &&
                StringUtil.isNotEmpty(user.getPassword())){
            if (userDao.selectByCellphone(user.getCellphone())!=null||userDao.selectByEmail(user.getEmail())!=null){
                return "exist";
            }else {
                PasswordEncoder encoderMd5 = new PasswordEncoder(Salt.SALT_STRING, "MD5");
                String password = encoderMd5.encode(user.getPassword());
                user.setPassword(password);
                user.setCreateTime(new Timestamp(new Date().getTime()));
                user.setState((byte) 1);
                user.setSalt(Salt.SALT_STRING);
                userDao.save(user);
                return "success";
            }
        }else {
            return "fail";
        }
    }

    @Override
    public User selectByCellphone(String cellphone) {
        return userDao.selectByCellphone(cellphone);
    }

    @Override
    public User selectByEmail(String email) {
        return userDao.selectByEmail(email);
    }

    @Override
    public User selectByCellphoneOrEmailAndPwd(String cellphone, String email, String password) {
        PasswordEncoder encoderMd5 = new PasswordEncoder(Salt.SALT_STRING,"MD5");
        String newPwd = encoderMd5.encode(password);
        return userDao.selectByCellphoneOrEmailAndPwd(cellphone,email,newPwd);
    }
}
